package org.example.tools;

import org.example.clientSendRead;
import org.example.pojo.clientInfo;

import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *  全程工具类
 */
public class utilsTools {
    public static Map<Socket, clientInfo> UserMaps = new HashMap<>();
    public static ThreadPoolExecutor threadPoolExecutor =new ThreadPoolExecutor(3,20,0, TimeUnit.SECONDS,new LinkedBlockingQueue(100), Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * dataDistribution  心跳检测
     * @param lzClass
     */
    public static void dataDistribution(Class lzClass){
        synchronized (lzClass){
            Set<Socket> infoSet = utilsTools.UserMaps.keySet();
            try {
                selectSocketSet(infoSet);
            }catch (Exception e){
                selectSocketSet(infoSet);
                dataDistribution(lzClass);
            }
        }
    }

    private static void selectSocketSet(Set<Socket> infoSet) {
        for (Socket socket :infoSet){
            try {
                socket.getOutputStream().write(0);
            }catch (Exception ioException){
                utilsTools.UserMaps.remove(socket);
                try {
                    socket.close();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                System.out.println("当前在线用户数:" + utilsTools.UserMaps.size() + "位");
                System.out.println("关闭集合了" );
            }
        }
    }


    /**
     * @param MapSocket 几何里的会话
     * @param csr  转出的接口
     */
    public static void selectSocketMaps(Set<Map.Entry<Socket, clientInfo>> MapSocket, clientSendRead csr) {
        csr.SocketData( MapSocket);
    }

    public static byte[] SocketDataByte(InputStream inputStream){
        try {
            byte[] dat = new byte[inputStream.available()];
            inputStream.read(dat);
            return dat;
        }catch (Exception e){e.printStackTrace();}
        return null;

    }

    /**
     * 取中间文本
     * @param allText  主要内容
     * @param index_x  左边
     * @param index_z  右边
     * @return  返回内容
     */
    public static String textCenter(String allText, String index_x, String index_z) {
        int index_head = allText.indexOf(index_x, 0);
        if (index_head >= 0) {
            index_head += index_x.length();
        }
        int index_end = allText.indexOf(index_z, index_head);
        if (index_head < 0 || index_end < 0) {
            return "";
        }
        String Addr = allText.substring(index_head, index_end);
        return Addr;
    }
}
